package org.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.example.realm.CustomRealm4;

/**
 * @author objcat
 * @version 1.0
 * @description 演示md5+盐加密认证
 * @date 2022/10/14 23:54
 */
public class App4 {
    public static void main(String[] args) {
        // 1.创建安全管理器对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // 2.给安全管理器设置ream, 从类名上我们就能看出来, 它是读取ini的
        CustomRealm4 realm = new CustomRealm4();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        securityManager.setRealm(realm);
        // 3.使用SecurityUtils进行认证, 设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        // 4.获取对象subject主体
        Subject subject = SecurityUtils.getSubject();
        // 5.根据用户名和密码创建一个认证对象
        UsernamePasswordToken token = new UsernamePasswordToken("objcat", "123456");
        try {
            // 首先打印登录前认证状态
            System.out.println("认证状态" + subject.isAuthenticated());
            // 进行登录
            subject.login(token);
            // 再次打印认证状态
            System.out.println("认证状态" + subject.isAuthenticated() + " 登录成功!");
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                System.out.println("用户名不存在");
            } else if (e instanceof IncorrectCredentialsException) {
                System.out.println("密码错误");
            }
            e.printStackTrace();
        }
    }
}
